package com.demo.drools.component;

import com.demo.drools.dal.orm.RuleTemplate;
import com.demo.drools.service.RuleTemplateService;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.definition.KiePackage;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhouSicheng
 * @description
 * @date 2019/3/15 15:09
 */
@Component
public class KieComponent {

    @Autowired
    private RuleTemplateService ruleTemplateService;

    private KieSession kieSession;

    private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    public void init() {
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            kieSession = null;
            System.out.println("kieSession 已被清空");
        }, 0L, 30L, TimeUnit.SECONDS);
    }

    public KieSession getKieSession() {
        if (null == kieSession) {

            List<RuleTemplate> templateList = ruleTemplateService.list();

            KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            templateList.forEach((template) -> builder.add(ResourceFactory.newByteArrayResource(template.getContent().getBytes(Charset.forName("UTF-8"))), ResourceType.DRL));
            InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
            Collection<KiePackage> knowledgePackages = builder.getKnowledgePackages();
            knowledgeBase.addPackages(knowledgePackages);
            kieSession = knowledgeBase.newKieSession();
            System.out.println("kieSession 已被加载");
        }
        return kieSession;
    }

}
